﻿<%@ Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage<SinBiota.Model.Entities.Occurrence>" %>
<%@ Import Namespace="Localization" %>

<asp:Content ID="Content1" ContentPlaceHolderID="TitleContent" runat="server">
	<%: Strings.AddSpecimensFromFile %>
</asp:Content>

<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">

    <h3><%: Strings.AddSpecimensFromFile %> - <%:Strings.Occurrence %> <%: Model.Id %> &nbsp;<span class="loading_img" style="display:none;"><img src="<%: Url.Content("~/Content/img/loading-big.gif") %>"/></span></h3>

    <div id="fileupload_div">
        <div class="alert-box">
            <%: Messages.OnlyXLSSupported %>
            <a href="" class="close">&times;</a>
        </div>

        <span class="small button radius"><%: Strings.File %>:
        <input id="fileupload" type="file" name="files[]" data-url='<%: Url.Action("ExcelFileUpload") %>' />
        </span>
    </div>

    <div id="select_sheet_div" style="display:none; margin-top:1em;">
    <form id="select_sheet_form" action="#">
         <div class="display-label"> 
            <%: Strings.SelectWorksheet%>
        </div>
        <div class="display-label"> 
            <select id="select_sheet" name="select_sheet"></select>
        </div>
        <a href="javascript:submit_sheet();" class="small button radius">OK</a>
        <a href="javascript:start_over();" class="small button radius">Cancel</a>
    </form>
    </div>

    <div id="select_columns_div" style="display:none; margin-top:1em;">

        <div id="error_messages_div" class="ui-widget validation-summary-errors" style="display:none;margin-bottom:1em;">
	        <div class="ui-state-error ui-corner-all" style="margin-top: 20px; padding: 0 .7em;">
		        <p><span class="ui-icon ui-icon-alert" style="float: left; margin-right: .3em;"></span>
		        <strong><%:Messages.PleaseCorrectTheErrorsBelow %></strong></p>
            <ul id="error_messages">
            </ul>
	        </div>
        </div>

    <form id="excel_data" action="">
         <div class="display-label"> 
            <%:Strings.IdentifyColumns %>
        </div>
        <div class="row">
            <div class="six columns">
                
                <fieldset style="min-height:100px;">
                <legend><%: Strings.Specimens %></legend>
                <input type="radio" name="classification_type" value="one_column" checked/><b><%: Strings.ClassificationInOneColumn%>:</b>
                <br /><br />
                <div class="left" style="margin-right:1em;"><%:Strings.ClassificationColumn %>: </div>
                <select id="one_column_classification" name="one_column_classification" class="col_select left"></select>
                <div class="clearfix"></div>

                <input type="radio" name="classification_type" value="different_columns"/><b><%:Strings.ClassificationInDifferent %>:</b><br /><br />
                
                <div class="left" style="margin-top:0.5em;"><%:Taxonomy.genero %>: </div>
                <select id="genus" name="genus" class="col_select left" style="position:absolute; left:8em; margin-top:0.5em;"></select>
                <div class="clearfix"></div>

                <div class="left" style="margin-top:0.5em;"><%:Taxonomy.especie %>:</div>
                <select id="species" name="species" class="col_select left" style="position:absolute; left:8em; margin-top:0.5em;"></select>
                <div class="clearfix"></div>

                <div class="left" style="margin-top:0.5em;"><%:Taxonomy.subespecie %>:</div>
                <select id="subspecies" name="subspecies" class="col_select left" style="position:absolute; left:8em; margin-top:0.5em;"></select>
                <div class="clearfix"></div>


                
                <br /><strong><%: Strings.NumberOfIndividualsOfEachSp %>:</strong><br />
                <input name="number_of_individuals" type="radio" value="one" checked /><%: Strings.One %><br />
                <input type="radio" name="number_of_individuals" value="unknown"/><%:Strings.Unknown %><br />
                <input type="radio" name="number_of_individuals" value="more" class="left"/>
                    <div class="left" style="margin-right:0.5em;"><%:Strings.MoreThanOne %> (<%:Strings.ChooseTheCorrespondingColumn %>):</div>
                    <select id="specimen_count" name="speciment_count" class="col_select left"></select>
                <div class="clearfix"></div>
                

                </fieldset>

            </div>
            <div class="six columns">



                <fieldset style="min-height:100px;">
                <legend><%:Strings.DepositaryUnit %> </legend>
                <input type="radio" name="depositary_unit_source" value="na" style="margin-bottom:1em;" checked />N.A.<br />
                <input type="radio" name="depositary_unit_source" value="column" class="left" /><div class="left" style="margin-right:1em;" ><%:Strings.FromColumn%>: </div> <select id="depositary_unit" name="depositary_unit" class="col_select left"></select>
                <div class="clearfix"></div>
                
                <input type="radio" name="depositary_unit_source" value="text" class="left"/><div class="left" style="margin-bottom:0.5em;"><%:Strings.FromText %>: </div>
                <input type="text" name="depositary_unit_text" id="depositary_unit_text" class="input-text left" style="width:300px;"/>
                <div class="clearfix"></div>

                <div class="left" style="margin-right:0.5em;"><%:Strings.RecordIdColumn %>:</div>
                <select id="record_id" name="record_id" class="col_select left"></select>
                <div class="clearfix"></div>

                </fieldset>
            </div>
        </div>

        <a href="javascript:submit_columns();" class="small button radius">OK</a>
        <a href="javascript:start_over();" class="small button radius">Cancel</a>
        <span class="loading_img" style="display:none;"><img src="<%: Url.Content("~/Content/img/loading.gif") %>"/></span>
        </form>
    </div>

    <div id="specimen_list_div" style="display:none; margin-top:1em;">
    <form action="" method="post">
        <fieldset><legend><%: Strings.SpeciesList %></legend>
            <div class="alert-box">
              <%: Messages.TaxonInRedIncluded %>
              <a href="" class="close">&times;</a>
            </div>
        <div class="row">
            <div class="six columns">
            <h4><%: Strings.SpeciesFromSheet %></h4>
            </div>
            <div class="six columns">
            <h4><%: Strings.ClassificationFound %></h4>
            </div>
        </div>
            <div id="specimen_list"></div>
        </fieldset>
        <input type="submit" class="small radius button" value="<%: Strings.AddSpecimens %>"/>
        <a href="javascript:start_over();" class="small button radius">Cancel</a>
    </form>
    </div>

    <script type="text/javascript">
        var file = "";
        var sheet = "";
        var is_waiting_ajax = false;

        function loading(b) {
            if (b) {
                $(".loading_img").show();
            }
            else {
                $(".loading_img").hide();
            }
        }
        function start_over() {
//            location.reload();
            hide_all();
            $("#fileupload_div").show();
        }
        function hide_all() {
            $("#select_sheet_div").hide();
            $("#select_columns_div").hide();
            $("#specimen_list_div").hide();
        }
        function createUploader() {

            $('#fileupload').fileupload({
                dataType: 'json',
                done: function (e, data) {
                    is_waiting_ajax = false;
                    analyze_upload_response(data.result);
                },
                submit: function () {
                    loading(true);
                    is_waiting_ajax = true;
                }

            });

        }
        function analyze_upload_response(result) {
            loading(false);
            if (!result.Success) {
                ErrorMessage('<b>' + result.Header + "</b><br>" + result.Message, result.Seconds);
                start_over()
                return;
            }
            InformationMessage('<b>' + result.Header + "</b><br>" + result.Message, result.Seconds);
            $("#fileupload_div").hide();
            // nome do arquivo:
            file = result.Data.file;
            // popula o option box para escolher qual aba:
            var select = $("#select_sheet");
            select.find('option').remove()
            $.each(result.Data.sheet_list, function () {
                select.append($("<option />").val(this.val).text(this.text));
            });
            // se só tiver 1, escolhe automático;
            if (result.Data.sheet_list.length == 1) {
                submit_sheet();
            }
            else {
                $("#select_sheet_div").show('slow');
            }
        }

        function submit_sheet() {
            if (is_waiting_ajax) return;
            is_waiting_ajax = true;
            loading(true);
            sheet = $("#select_sheet").val();
            $.ajax({
                type: "POST",
                url: '<%: Url.Action("SelectWorksheet") %>',
                data: "file=" + file + "&sheet=" + sheet,
                success: submit_sheet_return
            });
        }

        function submit_sheet_return(result) {
            is_waiting_ajax = false;
            loading(false);
            if (!result.Success) {
                ErrorMessage('<b>' + result.Header + "</b><br>" + result.Message, result.Seconds);
                start_over();
                return;
            }
            console.log(result.Success)
            //populate selects:
            $.each($(".col_select"), function () {
                var s = $(this);
                s.find('option').remove()
                s.append($("<option />").val(-1).text('  ---  '));
                $.each(result.Data.columns, function () {
                    s.append($("<option />").val(this.val).text(this.text));
                });
            });
            // hide and show:
            $("#select_sheet_div").hide();
            $("#select_columns_div").show('slow');

        }
        function submit_columns_validation() {
            var msg = [];
            console.log(class_type);
            var class_type = $("input:radio[name=classification_type]:checked").val();
            var one_column = $("#one_column_classification").val();
            var genus = $("#genus").val();
            var number_of_individuals = $("input:radio[name=number_of_individuals]:checked").val();
            var specimen_count = $("#specimen_count").val();
            
            var depositary_unit = $("#depositary_unit").val();
            var depositary_unit_source = $("input:radio[name=depositary_unit_source]:checked").val();
            var depositary_unit_text = $("#depositary_unit_text").val();
            var record_id = $("#record_id").val();

            if (class_type == 'one_column' && one_column < 0) {
                msg.push({ error: "<%= Messages.ChooseOneClassificationColumn %>" });
            }
            if (class_type == 'different_columns' && genus < 0) {
                msg.push({ error: "<%= Messages.ChooseGenusClassificationColumn %>" });
            }
            if (number_of_individuals == 'more' && specimen_count < 0) {
                msg.push({ error: "<%= Messages.ChooseSpeciesCountColumn %>" }); 
            }
            if (depositary_unit_source == 'column' && depositary_unit <0) {
                msg.push({ error: "<%= Messages.ChooseDUColumn %>" }); 
            }
            if (depositary_unit_source == 'text' && depositary_unit_text == "") {
                msg.push({ error: "<%= Messages.ChooseDUText %>" }); 
            }
            if (depositary_unit_source != 'na' && record_id < 0) {
                msg.push({ error: "<%= Messages.ChooseRecordIdColumn %>" }); 
            }


            return msg;
        }
        function submit_columns() {
            if (is_waiting_ajax) return;
            var messages = submit_columns_validation();
            if (messages.length > 0) {
                $("#error_messages").html($("#ErrorMessagesTemplate").render(messages));
                $("#error_messages_div").show('slow');
                return;
            }
            $("#error_messages_div").hide('slow');
            is_waiting_ajax = true;
            loading(true);

            $.ajax({
                type: "POST",
                url: '<%: Url.Action("ParseExcel") %>',
                data: {
                    classification_type: $("input:radio[name=classification_type]:checked").val(),
                    one_column_classification: $("#one_column_classification").val(),
                    genus: $("#genus").val(),
                    species: $("#species").val(),
                    subspecies: $("#subspecies").val(),
                    depositary_unit: $("#depositary_unit").val(),
                    depositary_unit_source: $("input:radio[name=depositary_unit_source]:checked").val(),
                    depositary_unit_text: $("#depositary_unit_text").val(),
                    record_id: $("#record_id").val(),
                    number_of_individuals: $("input:radio[name=number_of_individuals]:checked").val(),
                    specimen_count: $("#specimen_count").val(),
                    file: file,
                    sheet: sheet
                },
                success: submit_columns_return
            });
        }
        function submit_columns_return(result) {
            is_waiting_ajax = false;
            loading(false);
            if (!result.Success) {
                ErrorMessage('<b>' + result.Header + "</b><br>" + result.Message, result.Seconds);
                start_over();
                return;
            }
            hide_all();
            InformationMessage('<b>' + result.Header + "</b><br>" + result.Message, result.Seconds);
            //console.log(result.Data);
            $("#specimen_list").html($("#SpecimenParseTemplate").render(result.Data.list));
            $("#specimen_list_div").show('slow');

        }

        // INIT:
        $(document).ready(createUploader);
        $("#one_column_classification").click(function() { $("input:radio[name=classification_type]")[0].checked = true });
        $("#genus,#species,#subspecies").click(function () { $("input:radio[name=classification_type]")[1].checked = true });

        $("#depositary_unit").click(function () { $("input:radio[name=depositary_unit_source]")[1].checked = true });
        $("#depositary_unit_text").keyup(function () { $("input:radio[name=depositary_unit_source]")[2].checked = true });
        $("#specimen_count").click(function () { $("input:radio[name=number_of_individuals]")[2].checked = true });


        // set the 'append' name, that is, the new species taxon to be included below a genus taxon (empty string if not appending)
        function option_click(radio, idx) {
            var name = $(radio).attr('append_name');
            var rank = $(radio).attr('append_rank');
            $("#append_name_" + idx).val(name);
            $("#append_rank_" + idx).val(rank);
            if (name == "") {
                $("#reference_" + idx).hide('slow');
            }
            else {
                $("#reference_" + idx).show('slow');
            }

        }
    </script>    

</asp:Content>

<asp:Content ID="Content3" ContentPlaceHolderID="HeadContent" runat="server">
    <script src="<%: Url.Content("~/Scripts/highslide/highslide-with-html.min.js")%>" type="text/javascript"></script>
    <link href="<%: Url.Content("~/Scripts/highslide/highslide.css")%>" rel="stylesheet" type="text/css" />

<script type="text/javascript">
    hs.graphicsDir = '<%: Url.Content("~/Scripts/highslide/graphics/") %>';
    hs.showCredits = 0;
    hs.outlineType = 'rounded-white';
    hs.wrapperClassName = 'draggable-header';

</script>


    <script src="<%: Url.Content("~/Content/jquery-fileupload/vendor/jquery.ui.widget.js") %>" type="text/javascript"></script>
    <script src="<%: Url.Content("~/Content/jquery-fileupload/jquery.iframe-transport.js") %>" type="text/javascript"></script>
    <script src="<%: Url.Content("~/Content/jquery-fileupload/jquery.fileupload.js") %>" type="text/javascript"></script>

    <script type="text/javascript">
    var vars = {};

    $.views.tags({
        setvar: function(key, value) {
            vars[key] = value;
        }
    });

    $.views.helpers({
        getvar: function(key) {
            return vars[key];
        }
    })
    </script>
    <script id="ErrorMessagesTemplate" type="text/x-jsrender">
        <li>{{:error}}</li>
    </script>

    <script id="SpecimenParseTemplate" type="text/x-jsrender">
    <div class="row parse_specimen_item">
        {{setvar "count" #index /}}
        <div class="six columns">
            <b>{{:fullname}}</b><br>
            {{for classification}} 
                <i>{{:rank}}</i>: {{:taxon}}<br>
            {{/for}}
            <i><br><%: Strings.NumberOfIndividuals %>:</i> {{if count >0}}{{:count}}{{else}}<%:Strings.Unknown %>{{/if}}<br>
            {{if depositaryUnit != ""}}
                <br>
                <i><%: Strings.DepositaryUnit %></i>: {{:depositaryUnit}}<br>
                <i><%: Strings.Record %></i>: {{:recordId}}
            {{/if}}
        </div>
        <div class="six columns">
            {{if options.length > 0}}
                <input type="hidden" name="specimens[{{:~getvar('count')}}].AppendName" value="" id="append_name_{{:~getvar('count')}}">
                <input type="hidden" name="specimens[{{:~getvar('count')}}].AppendRank" value="" id="append_rank_{{:~getvar('count')}}">
                {{for options}}
                     <input type="radio" append_rank="{{:AppendRank}}" append_name="{{:AppendName}}" name='specimens[{{:~getvar('count')}}].Id' value='{{:Id}}'{{if #index == 0}} checked{{/if}} onclick="option_click(this, {{:~getvar('count')}});"/>
                     <span class="{{if Append}}red {{/if}}label round">{{:Rank}}</span>
                     &nbsp;&nbsp;<a href="<%:Url.Action("Lineage","Taxonomy") %>/{{:Id}}" class="highslide" onclick="return hs.htmlExpand(this, {objectType: 'ajax'})">{{:Name}}</a>
                     <span class="new_taxon">&nbsp;{{:AppendName}}</span> 
                     <div id="full_taxonomic_classification_{{:~getvar('count')}}_{{#index}}" style="display:none">
                     </div>
                     <br> 
                {{/for}}
                <input type="hidden" name="specimens[{{:~getvar('count')}}].DepositaryUnit" value="{{:depositaryUnit}}">
                <input type="hidden" name="specimens[{{:~getvar('count')}}].RecordId" value="{{:recordId}}" >
                <input type="hidden" name="specimens[{{:~getvar('count')}}].Count" value="{{:count}}" >
                <div id="reference_{{:~getvar('count')}}" style="display:none;">
                <br>
                <i><%:Strings.NewTaxonReference %>:</i> <input type="text" name="specimens[{{:~getvar('count')}}].Reference" value="" class="input-text">
                </div>
            {{else}}
            <div class="alert-box warning">
              <input type="hidden" name='specimens[{{:~getvar('count')}}].Id' value='-1'>
              <%: Messages.SpeciesClassificationNotFound %>
            </div>
            {{/if}}
        </div>
    </div>
    </script>
    
</asp:Content>
